/*
 * Copyright 2016. chenshufei
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package sz.szsmk.citizencard.util;


import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sz.szsmk.citizencard.DaggerApplication;

/**
 * String Utils
 *
 * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2011-7-22
 */
public class StringUtils {

    /**
     * is null or its length is 0 or it is made by space
     * <p/>
     * <pre>
     * isBlank(null) = true;
     * isBlank(&quot;&quot;) = true;
     * isBlank(&quot;  &quot;) = true;
     * isBlank(&quot;a&quot;) = false;
     * isBlank(&quot;a &quot;) = false;
     * isBlank(&quot; a&quot;) = false;
     * isBlank(&quot;a b&quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0 or it is made by space, return true, else return false.
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0);
    }

    /**
     * is null or its length is 0
     * <p/>
     * <pre>
     * isEmpty(null) = true;
     * isEmpty(&quot;&quot;) = true;
     * isEmpty(&quot;  &quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0, return true, else return false.
     */
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

    /**
     * compare two string
     *
     * @param actual
     * @param expected
     * @return
     */
    public static boolean isEquals(String actual, String expected) {


        return actual == expected || (actual == null ? expected == null : actual.equals(expected));
    }

    public static void hideInput(Activity activity){
        InputMethodManager systemService = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        systemService.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * null string to empty string
     * <p/>
     * <pre>
     * nullStrToEmpty(null) = &quot;&quot;;
     * nullStrToEmpty(&quot;&quot;) = &quot;&quot;;
     * nullStrToEmpty(&quot;aa&quot;) = &quot;aa&quot;;
     * </pre>
     *
     * @param str
     * @return
     */
    public static String nullStrToEmpty(String str) {
        return (str == null ? "" : str);
    }


    /**
     * 规则2：至少包含大小写字母及数字中的两种
     * 是否包含
     *
     * @param str
     * @return
     */
    public static boolean isLetterDigit(String str) {
        boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值，用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            } else if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        String regex = "^[a-zA-Z0-9]+$";
        boolean isRight = isDigit && isLetter && str.matches(regex);
        return isRight;
    }


    public static String doubleToString(double num) {
        //使用0.00不足位补0，#.##仅保留有效位
        return new DecimalFormat("0.00").format(num);
    }


    /**
     * capitalize first letter
     * <p/>
     * <pre>
     * capitalizeFirstLetter(null)     =   null;
     * capitalizeFirstLetter("")       =   "";
     * capitalizeFirstLetter("2ab")    =   "2ab"
     * capitalizeFirstLetter("a")      =   "A"
     * capitalizeFirstLetter("ab")     =   "Ab"
     * capitalizeFirstLetter("Abc")    =   "Abc"
     * </pre>
     *
     * @param str
     * @return
     */


    public static String capitalizeFirstLetter(String str) {
        if (isEmpty(str)) {
            return str;
        }

        char c = str.charAt(0);
        return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str
                : new StringBuilder(str.length()).append(Character.toUpperCase(c)).append(str.substring(1)).toString();
    }

    /**
     * encoded in utf-8
     * <p/>
     * <pre>
     * utf8Encode(null)        =   null
     * utf8Encode("")          =   "";
     * utf8Encode("aa")        =   "aa";
     * utf8Encode("啊啊啊啊")   = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
     * </pre>
     *
     * @param str
     * @return
     * @throws UnsupportedEncodingException if an error occurs
     */
    public static String utf8Encode(String str) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
            }
        }
        return str;
    }

    /**
     * encoded in utf-8, if exception, return defultReturn
     *
     * @param str
     * @param defultReturn
     * @return
     */
    public static String utf8Encode(String str, String defultReturn) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return defultReturn;
            }
        }
        return str;
    }

    /**
     * get innerHtml from href
     * <p/>
     * <pre>
     * getHrefInnerHtml(null)                                  = ""
     * getHrefInnerHtml("")                                    = ""
     * getHrefInnerHtml("mp3")                                 = "mp3";
     * getHrefInnerHtml("&lt;a innerHtml&lt;/a&gt;")                    = "&lt;a innerHtml&lt;/a&gt;";
     * getHrefInnerHtml("&lt;a&gt;innerHtml&lt;/a&gt;")                    = "innerHtml";
     * getHrefInnerHtml("&lt;a&lt;a&gt;innerHtml&lt;/a&gt;")                    = "innerHtml";
     * getHrefInnerHtml("&lt;a href="baidu.com"&gt;innerHtml&lt;/a&gt;")               = "innerHtml";
     * getHrefInnerHtml("&lt;a href="baidu.com" title="baidu"&gt;innerHtml&lt;/a&gt;") = "innerHtml";
     * getHrefInnerHtml("   &lt;a&gt;innerHtml&lt;/a&gt;  ")                           = "innerHtml";
     * getHrefInnerHtml("&lt;a&gt;innerHtml&lt;/a&gt;&lt;/a&gt;")                      = "innerHtml";
     * getHrefInnerHtml("jack&lt;a&gt;innerHtml&lt;/a&gt;&lt;/a&gt;")                  = "innerHtml";
     * getHrefInnerHtml("&lt;a&gt;innerHtml1&lt;/a&gt;&lt;a&gt;innerHtml2&lt;/a&gt;")        = "innerHtml2";
     * </pre>
     *
     * @param href
     * @return <ul>
     * <li>if href is null, return ""</li>
     * <li>if not match regx, return source</li>
     * <li>return the last string that match regx</li>
     * </ul>
     */
    public static String getHrefInnerHtml(String href) {
        if (isEmpty(href)) {
            return "";
        }

        String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
        Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
        Matcher hrefMatcher = hrefPattern.matcher(href);
        if (hrefMatcher.matches()) {
            return hrefMatcher.group(1);
        }
        return href;
    }

    //    把String转化为double
    public static double convertToDouble(String number, double defaultValue) {
        if (TextUtils.isEmpty(number)) {
            return defaultValue;
        }
        try {
            return Double.parseDouble(number);
        } catch (Exception e) {
            return defaultValue;
        }
    }


    /**
     * process special char in html
     * <p/>
     * <pre>
     * htmlEscapeCharsToString(null) = null;
     * htmlEscapeCharsToString("") = "";
     * htmlEscapeCharsToString("mp3") = "mp3";
     * htmlEscapeCharsToString("mp3&lt;") = "mp3<";
     * htmlEscapeCharsToString("mp3&gt;") = "mp3\>";
     * htmlEscapeCharsToString("mp3&amp;mp4") = "mp3&mp4";
     * htmlEscapeCharsToString("mp3&quot;mp4") = "mp3\"mp4";
     * htmlEscapeCharsToString("mp3&lt;&gt;&amp;&quot;mp4") = "mp3\<\>&\"mp4";
     * </pre>
     *
     * @param source
     * @return
     */
    public static String htmlEscapeCharsToString(String source) {
        return StringUtils.isEmpty(source) ? source
                : source.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&").replaceAll("&quot;", "\"");
    }

    /**
     * transform half width char to full width char
     * <p/>
     * <pre>
     * fullWidthToHalfWidth(null) = null;
     * fullWidthToHalfWidth("") = "";
     * fullWidthToHalfWidth(new String(new char[] {12288})) = " ";
     * fullWidthToHalfWidth("！＂＃＄％＆) = "!\"#$%&";
     * </pre>
     *
     * @param s
     * @return
     */
    public static String fullWidthToHalfWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == 12288) {
                source[i] = ' ';
                // } else if (source[i] == 12290) {
                // source[i] = '.';
            } else if (source[i] >= 65281 && source[i] <= 65374) {
                source[i] = (char) (source[i] - 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /**
     * transform full width char to half width char
     * <p/>
     * <pre>
     * halfWidthToFullWidth(null) = null;
     * halfWidthToFullWidth("") = "";
     * halfWidthToFullWidth(" ") = new String(new char[] {12288});
     * halfWidthToFullWidth("!\"#$%&) = "！＂＃＄％＆";
     * </pre>
     *
     * @param s
     * @return
     */
    public static String halfWidthToFullWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == ' ') {
                source[i] = (char) 12288;
                // } else if (source[i] == '.') {
                // source[i] = (char)12290;
            } else if (source[i] >= 33 && source[i] <= 126) {
                source[i] = (char) (source[i] + 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /**
     * 将手机号码13xxxxxxxxx替换为13x****xxxx
     *
     * @param phone
     * @return
     */
    public static String replacePhoneNo(String phone) {
        if (isEmpty(phone) || phone.length() < 11) {
            return phone;
        }
        String str1 = phone.substring(0, 3);
        String str2 = phone.substring(3, 7);
        String str3 = phone.substring(7);
        String subPhone = str1 + "****" + str3;
        return subPhone;
    }

    /**
     * 将价格转换为保留小数点后两位的字符串 展示
     *
     * @param price
     * @return
     */
    public static String decimalFormatPrice(int price) {
        return String.format("%.2f", price / 100.0);
    }

    public static String decimalFormatPrice(long price) {
        return String.format("%.2f", price / 100.0);
    }

    public static String decimalFormatPrice(String price) {
        double p = Double.valueOf(price);
        return String.format("%.2f", p / 100.0);
    }

    public static String decimalFormatPrice2(int price) {
        DecimalFormat df = new DecimalFormat("#,##0.00");
        return df.format(((double) price) / 100);
    }

    public static String decimalFormatHjbRate(double rate) {
        return new DecimalFormat("#,##0.0000").format(rate);
    }

    public static String decimalFormatFor2Rate(double rate) {
        return new DecimalFormat("#,##0.00").format(rate);
    }

    public static String decimalFormatHjbPrice(double price) {
        return new DecimalFormat("#,##0.00").format(price / 100);
    }

    public static String decimalFormatMoney(String amount) {
        return new DecimalFormat("#,##0.00").format(Double.valueOf(amount));
    }

    public static String decimalFormatHjb4Price(double price) {
        return new DecimalFormat("#,##0.0000").format(price / 100);
    }

    /**
     * 格式化人民币，
     *
     * @param money 分为单位
     * @return
     */
    public static String decimalRMB(long money) {
        long yun = money / 100;
        if (yun < 1) {
            return "0元";
        }
        StringBuffer sb = new StringBuffer();
        if (yun >= 10000) { //20002
            sb.append(yun / 10000).append("万");
        }

        if (yun > 1000 && yun > 10000) {
            yun = yun - ((yun / 10000) * 10000); //去掉万的，千
            if (yun / 1000 > 0) {
                sb.append(yun / 1000).append("千");
            }
        } else if (yun > 1000 && yun < 10000) {
            sb.append(yun / 1000).append("千");
            yun = yun - ((yun / 1000) * 1000); //去掉千
        }

        if (yun < 1000) {
            if (yun % 1000 > 0) {
                sb.append(yun % 1000);
            }
        }
        sb.append("元");

        return sb.toString();
    }

    /**
     * <乘法运算并保留两位有效数字> <功能详细描述>
     *
     * @param factor1 String
     * @param factor2 String
     * @return String
     */
    public static String multiply(String factor1, String factor2) {
        if (StringUtils.isEmpty(factor1)) {
            return "0";
        }
        if (StringUtils.isEmpty(factor2)) {
            return "0";
        }
        BigDecimal fac1 = new BigDecimal(factor1);
        BigDecimal fac2 = new BigDecimal(factor2);
        BigDecimal result = fac1.multiply(fac2);
        result = result.setScale(2, RoundingMode.HALF_UP);
        return result.toString();
    }


    public static boolean matchLuhn(String cardNo) {

        int[] cardNoArr = new int[cardNo.length()];

        for (int i = 0; i < cardNo.length(); i++) {
            cardNoArr[i] = Integer.valueOf(String.valueOf(cardNo.charAt(i)));

        }
        for (int i = cardNoArr.length - 2; i >= 0; i -= 2) {
            cardNoArr[i] <<= 1;
            cardNoArr[i] = cardNoArr[i] / 10 + cardNoArr[i] % 10;

        }
        int sum = 0;
        for (int i = 0; i < cardNoArr.length; i++) {
            sum += cardNoArr[i];
        }
        return sum % 10 == 0;
    }

    /**
     * <除法运算并保留两位有效数字> <功能详细描述>
     *
     * @param divisor1 String
     * @param divisor2 String
     * @return String
     */
    public static String divide(String divisor1, String divisor2) {
        if (StringUtils.isEmpty(divisor1)) {
            return "0.00";
        }
        BigDecimal div1 = new BigDecimal(divisor1);
        BigDecimal div2 = new BigDecimal(divisor2);
        BigDecimal result = div1.divide(div2, 2, RoundingMode.HALF_UP);
        return result.toString();
    }


    /**
     * A卡判断
     */


    public static boolean isACard(String etCard) {
        boolean isAcard = false;
        String start = etCard.substring(0, 1);
        String end = etCard.substring(etCard.length() - 1, etCard.length());
        String substring = etCard.substring(1, etCard.length() - 1);
        String num = etCard.substring(1, etCard.length());

        if (start.equals("A") || start.equals("a")) {
            if (end.equals("X") && isNumeric(substring) && etCard.length() == 9) {
                isAcard = true;
            }
            if (end.equals("x") && isNumeric(substring) && etCard.length() == 9) {
                isAcard = true;
            }
        }


        if (start.equals("A") || start.equals("a")) {
            if (isNumeric(num) && etCard.length() == 9) {
                isAcard = true;
            } else {
                isAcard = false;
            }
        } else {
            isAcard = false;
        }

        return false;
    }

    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }



    /**
     * <保留两位有效数字> <功能详细描述>
     *
     * @param num String
     * @return String
     */
    public static String retained2SignificantFigures(String num) {
        return new BigDecimal(num).setScale(2, RoundingMode.HALF_UP).toString();
    }

    // yyyy-MM-dd HH:mm:ss 解析成年月日
    public static String timeDayByDay(String date) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse(date);
        // Date date1 = DateTimeUtil.stringToDateTime(date);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        String str = formatter.format(date1);
        return str;
    }

    // yyyy-MM-dd HH:mm:ss 解析成年月日
    public static String timeByDay(String date) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // Date date1 = sdf.parse(date);
        Date date1 = DateTimeUtil.stringToDateTime(date);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        String str = formatter.format(date1);
        return str;
    }

    // yyyy-MM-dd HH:mm:ss 解析成年月日 时分
    public static String timeBymin(String date) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // Date date1 = sdf.parse(date);
        Date date1 = DateTimeUtil.stringToDateTime(date);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String str = formatter.format(date1);
        return str;
    }

    /***
     * 除了前三位和后四位 中间位数置为*
     * 用于隐藏手机号中间位数
     *
     * @param str
     * @return
     */
    public static String getHideMidStr(String str) {
        if (str == null) {
            return null;
        }
        StringBuffer result = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            result.append((i < 3 || i >= len - 4) ? str.charAt(i) : "*");
        }
        return result.toString();
    }

    /**
     * 判断手机格式是否正确
     *
     * @return
     */
    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$";
        if (phone.length() != 11) {
            Toast.makeText(DaggerApplication.getIns(), "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
//            LogUtil.e(isMatch);
            if (!isMatch) {
                Toast.makeText(DaggerApplication.getIns(), "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            }
            return isMatch;
        }
    }


    /***
     * 除了前四位和后四位 中间位数置为*
     * 用于隐藏银行卡号中间位数
     *
     * @param str
     * @return
     */
    public static String getHideMidStr2(String str) {
        if (str == null) {
            return null;
        }
        StringBuffer result = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            result.append((i < 4 || i >= len - 4) ? str.charAt(i) : "*");
        }
        return result.toString();
    }

    /****
     * 获取字符串末尾n位
     *
     * @param str
     * @param n   末尾位数
     * @return
     */
    public static String getEndStr(String str, int n) {
        if (str != null && str.length() > n) {
            return str.substring(str.length() - n);
        }
        return str;
    }

    /**
     * 获取七日年化收益率，如果字符格式为x-x，取前一个
     *
     * @param sdGains
     * @return
     */
    public static String getProfit(String sdGains) {
        if (sdGains.indexOf("-") == -1) {//不包含
            return sdGains;
        } else {
            String[] array = sdGains.split("-");
            return array[0];
        }
    }

    /**
     * 提供精确的加法运算
     *
     * @param v1
     * @param v2
     * @return 两个参数数学加和，以字符串格式返回
     */
    public static String add(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.add(b2).toString();
    }

    /**
     * @param _money
     * @return 金额格式控制
     */
    public static String formatMoney(String _money) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        String formatMoney = decimalFormat.format(Double.parseDouble(_money));
        return formatMoney;
    }



}
